<template>
  <div>
    <g-dynamic-table
      type="roles"
      ref="table"
      :fetch="fetchDataList"
      :showActionBtn="showActionBtn"
      :showExport="true"
      @action-click="handleActionClick"
    >
      <template #headerCell="{ column }">
        <template v-if="column.field == 'No'">
          {{ column.title }}
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'displayName'">
          <span>{{ record.displayName }}</span>
          <a-tag v-if="record.isStatic" color="#108ee9"> {{ l('Static') }}</a-tag>
          <a-tag v-if="record.isDefault" color="#2db7f5"> {{ l('Default') }}</a-tag>
        </template>
      </template>
    </g-dynamic-table>
  </div>
</template>
<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import { RoleListDto, RoleServiceProxy } from '/@/shared/service-proxies';
  import CreateEditRoleCompent from './create-or-edit-role/create-or-edit-role.vue';
  import { defineComponent } from 'vue';
  import _ from 'lodash';
  import { AppConsts } from '/@/abpPro/AppConsts';
  import GDynamicTable from '/@/shared/components/g-dynamic-table/index.vue';
  import { EVENT_BTN_ENUM } from '/@/shared/components/g-dynamic-table/enums/event-btn-enum';
  export default defineComponent({
    name: 'roles-news',
    components: {
      GDynamicTable,
      CreateEditRoleCompent,
    },
    mixins: [AppComponentBase],
    data() {
      return {
        roleServiceProxy: new RoleServiceProxy(),
        // 选中的权限过滤
        selectedPermission: [] as any,

        // 请求参数
        filterText: undefined,
        dataList: [] as RoleListDto[],
        /** 选中 */
        selectItems: [] as any[],
      };
    },
    computed: {
      showActionBtn() {
        /**
         * item 按钮json配置项
         * column table 当前列配置
         * record 当前行数据
         */
        return (item, column, record) => {
          switch (item.name) {
            case EVENT_BTN_ENUM.DELETE:
              return !record.isStatic && record.name !== 'Admin';
            default:
              return true;
          }
        };
      },
    },
    mounted() {
      (this.$refs.table as any).setRowSelection('getCheckboxProps', (record) => {
        return {
          disabled: record.isStatic && record.name == 'Admin',
        };
      });
    },
    methods: {
      /**
       * 获取数据
       */
      fetchDataList(otherQuery) {
        const { maxResultCount, skipCount, sorting, Permissions, RoleName, CreationTime } = (
          this.$refs.table as any
        ).getSearchProps();
        return new Promise((resolve, reject) => {
          this.roleServiceProxy
            .getPaged(
              Permissions,
              !CreationTime ? undefined : CreationTime[0],
              !CreationTime ? undefined : CreationTime[1],
              RoleName,
              sorting,
              !!otherQuery ? otherQuery.maxResultCount : maxResultCount,
              !!otherQuery ? otherQuery.skipCount : skipCount,
            )
            .finally(() => {
              // finishedCallback!();
            })
            .then((res) => {
              resolve(res);
              // this.showPaging(res);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },
      /**
       * table默认配置 （是否禁用）
       */
      getCheckboxProps(record) {
        return {
          disabled: record.displayName == 'Admin',
          name: record.displayName,
        };
      },
      /**
       * 添加角色  修改角色
       */
      createOrEdit(item?: RoleListDto) {
        this.selectItems = [];
        // this.item = !!item ? item : ({} as UserListDto);
        if (!!item && item.id) {
          this.selectItems = [item.id];
        }
        this.modalHelper
          .create(CreateEditRoleCompent, { pageDataList: this.selectItems })
          .subscribe((res) => {
            if (res) {
              (this.$refs.table as any).reloadGoFirstPage();
            }
          });
      },
      /**
       * 批量删除
       */
      batchDelete() {
        const table = this.$refs.table as any;
        if (table.getSelectRowKeys().length <= 0) {
          this.notify.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', table.getSelectRowKeys().length),
          '',
          (res) => {
            if (res) {
              const ids = [...table.getSelectRowKeys()];
              (this.$refs.table as any).setLoading(true);
              this.roleServiceProxy
                .batchDelete(ids)
                .finally(() => {
                  (this.$refs.table as any).setLoading(false);
                })
                .then(() => {
                  (this.$refs.table as any).reloadGoFirstPage();
                  this.notify.success(this.l('SuccessfullyDeleted'));
                });
            }
          },
        );
      },
      /**
       * 单个删除
       */
      deleteItem(item: RoleListDto) {
        if ((item as any).isStatic) {
          this.notify.warn(
            this.l('XUserCannotBeDeleted', AppConsts.userManagement.defaultAdminUserName),
          );
          return;
        }
        (this.$refs.table as any).setLoading(true);
        this.roleServiceProxy
          .delete(item.id)
          .finally(() => {
            (this.$refs.table as any).setLoading(false);
          })
          .then(() => {
            (this.$refs.table as any).reloadGoFirstPage();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      },
      /**
       * 批量编辑
       */
      bulkEdit() {
        this.selectItems = [];
        let arr = (this.$refs.table as any).getSelectRowKeys();
        if (arr.length < 1) {
          return this.notify.warn(this.l('PleaseSelectAtLeastOneItem'));
        }
        this.selectItems = arr;
        this.modalHelper
          .create(CreateEditRoleCompent, { pageDataList: this.selectItems })
          .subscribe((res) => {
            if (res) {
              (this.$refs.table as any).reloadGoFirstPage();
            }
          });
      },
      /**
       * 按钮回调事件
       */
      handleActionClick(event: string, item?: any) {
        console.log(event);
        switch (event) {
          case EVENT_BTN_ENUM.CREATE:
            this.createOrEdit();
            break;
          case EVENT_BTN_ENUM.BULK_EDIT:
            this.bulkEdit();
            break;
          case EVENT_BTN_ENUM.DELETE:
            this.deleteItem(item);
            break;
          case EVENT_BTN_ENUM.BULK_DELETE:
            this.batchDelete();
            break;
          case EVENT_BTN_ENUM.EDIT:
            this.createOrEdit(item);
            break;
          default:
            break;
        }
      },
    },
  });
</script>
